package cn.ltw.android_threadtest;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private int progress = 0;
    private boolean isPause = false;

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int action = intent.getIntExtra("action", -1);
        switch (action) {
            case 1:
               if (isPause) {
                   isPause =false;
                   synchronized (this) {
                       this.notify();
                   }
               }
               else
                    play();
                break;
            case 2:
                pause();
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public class MyBinder extends Binder {
        public int getProgress() {
            return progress;
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public void play() {
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 800; i++) {
                   synchronized (MyService.this) {
                       if (isPause) {
                           try {
                               MyService.this.wait();
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                       }
                       try {
                           Thread.sleep(20);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                       progress++;
                  }
                }
            }

        }.start();

    }

    public void pause() {
        isPause = true;

    }
}
